<template>
  <div class="col row justify-center">
    <q-field class="col" dense v-model="fileId" borderless :rules="rules" :hide-bottom-space="true" :lazy-rules="true">
      <template v-slot:control class="column items-center justify-start">
        <vue-preview v-if="imageUpload && hasFile" style="max-width:120px;display:inline-block;" :slides="imagePath()" class="preview"></vue-preview>
        <q-btn flat dense unelevated color="primary" @click="downloadFile()" :label="fileName" :disable="!(download && hasFile)" v-if="!imageUpload && hasFile">
          <q-tooltip>下载附件</q-tooltip>
        </q-btn>
        <div class="rounded-borders">
          <q-btn label="上传" icon="mdi-cloud-upload-outline" :loading="importing" class="q-mr-sm" color="primary" @click="uploadFiles" v-if="upload && !hasFile && !(readonly || disable)">
            <q-tooltip>上传</q-tooltip>
            <q-uploader auto-upload ref="fileUploader" :max-files="1000" :multiple="false" class="hidden" :url="uploadUrl" field-name="file" :form-fields="formFields" :accept="accept" :headers="headers" :max-file-size="maxSize" @uploaded="uploadedFiles" @rejected="rejectedFiles" />
          </q-btn>
          <btn-file-del v-if="del && hasFile && !(readonly || disable)" label="附件" @confirm="delFile()" />
        </div>
      </template>
    </q-field>
  </div>
</template>

<script>

export default {
  name: 'SubUpload',
  components: {},
  props: {
    rules: {
      type: Array,
      required: false,
      default: () => [],
    },
    required: Boolean,
    readonly: Boolean,
    accept: {
      type: String,
      default: '*',
    },
    formData: {
      type: Object,
    },
    formKey: {
      type: String,
    },
    imageUpload: {
      type: Boolean,
      default: false,
    },
    upload: {
      type: Boolean,
      required: false,
      default: true,
    },
    download: {
      type: Boolean,
      required: false,
      default: true,
    },
    del: {
      type: Boolean,
      required: false,
      default: true,
    },
    disable: [Boolean, Object],
  },
  data() {
    return {
      maxSize: 20 * 1024 * 1024,
      formFields: [],
      hasFile: false,
      importing: false,
      headers: [{ name: 'Authorization', value: localStorage.Authorization }],
      uploadUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/dynUpload`,
      imgUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/dynView`,
      selectFile: {},
      fileId: '',
      fileName: '',
      imageList: [],
    };
  },
  methods: {
    rejectedFiles(rejectedEntries) {
      rejectedEntries.forEach((rejectedFile) => {
        if (rejectedFile.failedPropValidation === 'max-file-size') {
          const { file } = rejectedFile;
          this.$error(`(${file.name})上传失败， 目前支持上传最大${this.maxSize / 1024 / 1024}MB`);
        }
      });
    },
    empty() {

    },
    imagePath() {
      let path = '';
      if (this.hasFile) {
        path = `${this.imgUrl}/${this.formData[this.formKey]}`;
      }

      return [{
        msrc: path,
        src: path,
        w: 600,
        h: 800,
      }];
    },
    uploadFiles() {
      this.$refs.fileUploader.pickFiles();
      this.formFields = [
        { name: 'formId', value: 'sub-upload' },
        { name: 'dataId', value: 'sub-upload' },
        { name: 'fieldId', value: 'sub-upload' }];
    },
    uploadedFiles({ xhr }) {
      this.$refs.fileUploader.removeUploadedFiles();
      const { response } = xhr;
      const res = JSON.parse(response);
      if (res.code === 200) {
        this.formData[this.formKey] = res.result.id;
        this.formData[`${this.formKey}_text`] = res.result.name;
        this.fileId = res.result.id;
        this.fileName = res.result.name;
        this.hasFile = true;
      } else {
        this.$error(res.message);
      }
    },
    downloadFile() {
      const id = this.formData[this.formKey];
      this.$axios.get(`/dyn/file/queryById?id=${id}`).then(({ result }) => {
        this.doDownloadFile(result);
      });
    },
    doDownloadFile(row) {
      this.exporting = true;
      this.$downFile('/dyn/file/downloads', {
        id: row.id,
      }).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败');
          return;
        }
        window.open(`${process.env.SERVER_URL}${process.env.BASE_URL}/dyn/file/downloads?id=${row.id}`);
      }).finally(() => {
        this.exporting = false;
      });
    },
    delFile() {
      this.formData[this.formKey] = null;
      this.formData[`${this.formKey}_text`] = null;
      this.fileId = null;
      this.fileName = null;
      this.hasFile = false;
    },
    init() {
      if (this.formData) {
        this.fileId = this.formData[this.formKey];
        this.fileName = this.formData[`${this.formKey}_text`];
        if (this.fileId) {
          this.hasFile = true;
        } else {
          this.hasFile = false;
        }
      }
    },
  },
  created() { },
  mounted() {
    this.maxSize = process.env.MAX_FILE_SIZE;
    this.init();
  },
  watch: {
    formData: {
      handler() {
        this.init();
      },
      deep: true,
    },
  },
  computed: {

  },
};
</script>
<style lang="stylus">
.preview
  figure
    margin-block-start 0px
    margin-block-end 0px
    margin-inline-start 0px
    margin-inline-end 0px
    img
      width 100%
      height 75%
</style>
